/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Login.java
 *
 * Created on Nov 17, 2011, 7:56:54 PM
 */
package view;

import bll.UserBLL;
import bean.NguoiDung;
import javax.swing.*;
import java.awt.Graphics;
import java.awt.event.KeyEvent;

/**
 *
 * @author HoangNam
 *
 */
public class Login extends MasterForm {

    private ImageIcon bgImage;
    private JPanel panel;
    private UserBLL userBLL;

    /**
     * Creates new form Login
     */
    public Login() {
        formatForm();
        initComponents();
    }

    private void formatForm() {
        bgImage = null;
        this.setSize(100, 200);
        panel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                if (bgImage != null) {
                    g.drawImage(bgImage.getImage(), 0, 0, getWidth(), getHeight(), null);
                }
            }
        };
        setContentPane(panel);
        FormatForm();
        bgImage = new ImageIcon(getClass().getResource("/image/background_login.jpg"));
        setIconImage(new ImageIcon(getClass().getResource("/image/login.png")).getImage());
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lbUsername = new javax.swing.JLabel();
        txtUsername = new javax.swing.JTextField();
        lbPassword = new javax.swing.JLabel();
        pwdPassword = new javax.swing.JPasswordField();
        btLogin = new javax.swing.JButton();
        btnExit = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Đăng nhập");
        setResizable(false);

        lbUsername.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N
        lbUsername.setForeground(new java.awt.Color(255, 255, 255));
        lbUsername.setText("Tên đăng nhập");

        txtUsername.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtUsernameKeyPressed(evt);
            }
        });

        lbPassword.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N
        lbPassword.setForeground(new java.awt.Color(255, 255, 255));
        lbPassword.setText("Mật khẩu");

        pwdPassword.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                pwdPasswordKeyPressed(evt);
            }
        });

        btLogin.setFont(new java.awt.Font("Dialog", 1, 12)); // NOI18N
        btLogin.setForeground(new java.awt.Color(0, 51, 51));
        btLogin.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/login_button.png"))); // NOI18N
        btLogin.setText("Đăng nhập");
        btLogin.setMaximumSize(new java.awt.Dimension(100, 25));
        btLogin.setMinimumSize(new java.awt.Dimension(100, 25));
        btLogin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btLoginActionPerformed(evt);
            }
        });

        btnExit.setFont(new java.awt.Font("Dialog", 1, 12)); // NOI18N
        btnExit.setForeground(new java.awt.Color(0, 51, 51));
        btnExit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/image/Exit.png"))); // NOI18N
        btnExit.setText("Thoát");
        btnExit.setMaximumSize(new java.awt.Dimension(100, 25));
        btnExit.setMinimumSize(new java.awt.Dimension(100, 25));
        btnExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExitActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(68, 68, 68)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(lbUsername, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(lbPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(8, 8, 8)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(pwdPassword, javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(0, 0, Short.MAX_VALUE)
                                .addComponent(btLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(26, 26, 26)
                                .addComponent(btnExit, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtUsername)))
                .addGap(122, 122, 122))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(106, 106, 106)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbUsername)
                    .addComponent(txtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(29, 29, 29)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(pwdPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbPassword))
                .addGap(32, 32, 32)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(btLogin, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnExit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(78, Short.MAX_VALUE))
        );

        setSize(new java.awt.Dimension(550, 366));
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void btnExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExitActionPerformed
        System.exit(0);
}//GEN-LAST:event_btnExitActionPerformed

    private void btLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btLoginActionPerformed
        login();
}//GEN-LAST:event_btLoginActionPerformed

    private void txtUsernameKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtUsernameKeyPressed
        int key = evt.getKeyCode();
        if (key == KeyEvent.VK_ENTER && pwdPassword.getPassword().length != 0 && !txtUsername.getText().trim().isEmpty()) {
            login();
        }
}//GEN-LAST:event_txtUsernameKeyPressed

    private void pwdPasswordKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_pwdPasswordKeyPressed
        int key = evt.getKeyCode();
        if (key == KeyEvent.VK_ENTER && pwdPassword.getPassword().length != 0 && !txtUsername.getText().trim().isEmpty()) {
            login();
        }
    }//GEN-LAST:event_pwdPasswordKeyPressed
    /**
     * @param args the command line arguments
     */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btLogin;
    private javax.swing.JButton btnExit;
    private javax.swing.JLabel lbPassword;
    private javax.swing.JLabel lbUsername;
    private javax.swing.JPasswordField pwdPassword;
    private javax.swing.JTextField txtUsername;
    // End of variables declaration//GEN-END:variables

    /**
     * private void setBackground() { ImageIcon imageIcon = new
     * ImageIcon("src\\image\\header.jpg"); backgroundImage = imageIcon; }
     */
    private void login() {

        char[] passWord = pwdPassword.getPassword();
        if (txtUsername.getText().trim().equals("")) {
            displayFailure("Vui lòng nhập tên đăng nhập");
            txtUsername.requestFocusInWindow();
            return;
        } else if (passWord.length == 0) {
            displayFailure("Vui lòng nhập mật khẩu");
            pwdPassword.requestFocusInWindow();
            return;
        }

        try {
            StringBuilder pass = new StringBuilder();
            for (char c : passWord) {
                pass.append(c);
            }

            userBLL = new UserBLL();
            NguoiDung user = userBLL.login(txtUsername.getText(), pass.toString());
            if (user == null) {
                displayFailure("Thông tin đăng nhập không chính xác");
                txtUsername.requestFocusInWindow();
            } else {

                MainForm mainForm = new MainForm();
                mainForm.setTitle("Hệ thống quản lý cửa hàng thời trang - Đăng nhập bởi " + user.getThongTinNguoiDung().getTen());
                mainForm.setExtendedState(JFrame.MAXIMIZED_BOTH);
                mainForm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                mainForm.setIconImage(new javax.swing.ImageIcon(getClass().getResource("/image/clothes.png")).getImage());
                mainForm.setBackground(new javax.swing.ImageIcon(getClass().getResource("/image/background2.jpg")));
                mainForm.setVisible(true);
                this.dispose();
            }
        } catch (Exception ex) {
            displayFailure("Vui lòng kiểm tra kết nối đến cơ sở dữ liệu.");
            System.out.println(ex);
        }
    }
}
